package com.waves.design.prototype.scene;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class PrototypeExample implements Cloneable{
    private List<String> data;

    public PrototypeExample() {
        data = new ArrayList<>();
        data.add("Initial data");
    }

    public void addData(String item) {
        data.add(item);
    }

    public List<String> getData() {
        return data;
    }

    @Override
    protected PrototypeExample clone() throws CloneNotSupportedException {
        PrototypeExample cloned = (PrototypeExample) super.clone();
        cloned.data = new ArrayList<>(data);
        return cloned;
    }
}

class PrototypePatternInMultiThreading {
    public static void main(String[] args) throws InterruptedException {
        PrototypeExample original = new PrototypeExample();
        original.addData("More data for original");

        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 5; i++) {
            executorService.submit(() -> {
                try {
                    PrototypeExample cloned = original.clone();
                    cloned.addData("Data added in thread");
                    System.out.println("Cloned object data in thread: " + cloned.getData());
                } catch (CloneNotSupportedException e) {
                    e.printStackTrace();
                }
            });
        }

        executorService.shutdown();
        while (!executorService.isTerminated()) {
            Thread.sleep(100);
        }

        System.out.println("Original object data: " + original.getData());
    }
}
